/*
 * @lc app=leetcode.cn id=919 lang=typescript
 *
 * [919] 完全二叉树插入器
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

class CBTInserter {
  root: TreeNode | null;
  // 没有左右子节点的节点
  candidate: TreeNode[] = [];
  constructor(root: TreeNode | null) {
    this.root = root;
    const queue = [root];
    while (queue.length) {
      const node = queue.shift();
      if (node.left) {
        queue.push(node.left);
      }
      if (node.right) {
        queue.push(node.right);
      }
      if (!node.right) {
        this.candidate.push(node);
      }
    }
  }

  insert(val: number): number {
    const child = new TreeNode(val);
    const parent = this.candidate[0];
    if (!parent.left) {
      parent.left = child;
    } else {
      parent.right = child;
      this.candidate.shift();
    }
    this.candidate.push(child);
    return parent.val;
  }

  get_root(): TreeNode | null {
    return this.root;
  }
}

/**
 * Your CBTInserter object will be instantiated and called as such:
 * var obj = new CBTInserter(root)
 * var param_1 = obj.insert(val)
 * var param_2 = obj.get_root()
 */
// @lc code=end
